import 'package:flutter/material.dart';
import '../../api/collect.dart'; // 使用新封装的CollectAPI
import '../../models/collect_list_item.dart';
import '../../models/response.dart';
import '../../routes/app_routes.dart';
import '../../screens/post_detail_screen.dart';
import '../../utils/app_constants.dart'; // 包含successCode的常量文件

class AppConstants {
  static const int successCode = 1000; // 定义successCode为1000
  static const int defaultPageSize = 10; // 定义defaultPageSize为10
}

class CollectionListPage extends StatefulWidget {
  const CollectionListPage({super.key});

  @override
  State<CollectionListPage> createState() => _CollectionListPageState();
}

class _CollectionListPageState extends State<CollectionListPage> {
  // 选择模式状态
  bool _isSelecting = false;
  final Set<int> _selectedItems = {};

  // API服务 - 使用新封装的CollectAPI
  final CollectAPI _collectApi = CollectAPI();

  // 实际收藏数据
  List<CollectListItem> _collectedPosts = [];

  // 加载状态
  bool _isLoading = true;
  String? _errorMessage;

  // 分页控制
  int _currentPage = 1;
  final int _pageSize = AppConstants.defaultPageSize;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _fetchCollections();
  }

  // 获取收藏数据 - 使用新API
  Future<void> _fetchCollections({bool loadMore = false}) async {
    try {
      if (!loadMore) {
        setState(() {
          _isLoading = true;
          _errorMessage = null;
        });
      }

      // 调用新API获取数据 - 需实现getCollections方法
      final ResponseSuccess<List<CollectListItem>> response =
      await _collectApi.getCollections(page: _currentPage);

      // 处理响应
      if (response.code == AppConstants.successCode) {
        final newItems = response.data ?? [];
        setState(() {
          if (loadMore) {
            _collectedPosts.addAll(newItems);
          } else {
            _collectedPosts = newItems;
          }

          // 检查是否有更多数据
          _hasMore = newItems.length >= _pageSize;
          _isLoading = false;
        });

        if (newItems.isNotEmpty) {
          _currentPage++;
        }
      } else {
        setState(() {
          _errorMessage = response.msg ?? '获取收藏数据失败';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  // 进入/退出选择模式
  void _toggleSelectMode() {
    setState(() {
      _isSelecting = !_isSelecting;
      if (!_isSelecting) {
        _selectedItems.clear();
      }
    });
  }

  // 切换单条记录的选中状态
  void _toggleSelection(int index) {
    setState(() {
      if (_selectedItems.contains(index)) {
        _selectedItems.remove(index);
      } else {
        _selectedItems.add(index);
      }
    });
  }

  // 执行删除操作 - 使用新的uncollectPost方法
  Future<void> _deleteSelected() async {
    if (_selectedItems.isEmpty) return;

    try {
      // 获取要删除的帖子ID列表
      final List<String> postIds = _selectedItems
          .map((index) => _collectedPosts[index].postId)
          .toList();

      // 显示加载状态
      setState(() {
        _isLoading = true;
      });

      // 依次调用删除API - 使用新API的uncollectPost方法
      for (final postId in postIds) {
        await _collectApi.uncollectPost(postId);
      }

      // 删除成功后刷新列表
      await _fetchCollections();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('删除收藏成功')),
        );
      }
    } catch (e) {
      setState(() {
        _errorMessage = '删除操作失败: $e';
        _isLoading = false;
      });

      // 显示错误信息
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_errorMessage!)),
        );
      }
    } finally {
      setState(() {
        _isSelecting = false;
        _selectedItems.clear();
      });
    }
  }

  // 单个删除收藏
  Future<void> _deleteSingleItem(String postId) async {
    try {
      setState(() {
        _isLoading = true;
      });
      await _collectApi.uncollectPost(postId);
      await _fetchCollections();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('删除成功')),
        );
      }
    } catch (e) {
      setState(() {
        _errorMessage = '删除失败: $e';
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_errorMessage!)),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 清空所有收藏
  Future<void> _clearAllCollections() async {
    if (_collectedPosts.isEmpty) return;

    try {
      setState(() {
        _isLoading = true;
      });

      for (final post in _collectedPosts) {
        await _collectApi.uncollectPost(post.postId);
      }

      await _fetchCollections(); // Refresh after clearing all
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已清空所有收藏')),
        );
      }
    } catch (e) {
      setState(() {
        _errorMessage = '清空失败: $e';
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_errorMessage!)),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
        _isSelecting = false;
        _selectedItems.clear();
      });
    }
  }

  // 跳转到帖子详情页
  void _navigateToPostDetail(CollectListItem post) {
    Navigator.of(context).pushNamed(
      AppRoutes.postDetailScreen,
      arguments: post.postId, // ✅ 直接传递 String
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的收藏'),
        actions: [
          if (_collectedPosts.isNotEmpty && !_isLoading)
            IconButton(
              icon: Icon(
                _isSelecting ? Icons.close : Icons.select_all,
                color: _isSelecting ? Colors.black : Colors.deepOrange,
              ),
              onPressed: _toggleSelectMode,
            ),
          if (_collectedPosts.isNotEmpty && !_isLoading)
            IconButton(
              icon: const Icon(Icons.clear_all, color: Colors.deepOrange),
              onPressed: _clearAllCollections,
            ),
        ],
      ),
      body: _buildBody(),
      floatingActionButton: _isSelecting
          ? null
          : FloatingActionButton(
        onPressed: () => _fetchCollections(),
        tooltip: '刷新',
        child: const Icon(Icons.refresh),
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading && _collectedPosts.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '加载失败: $_errorMessage',
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _fetchCollections(),
              child: const Text('重试'),
            )
          ],
        ),
      );
    }

    if (_collectedPosts.isEmpty) {
      return const Center(
        child: Text(
          '暂无收藏内容',
          style: TextStyle(color: Colors.grey, fontSize: 16),
        ),
      );
    }

    return Stack(
      children: [
        // 主内容区域
        ListView.builder(
          padding: EdgeInsets.only(
            left: 16.0,
            right: 16.0,
            top: 8.0,
            bottom: _isSelecting ? 100 : 0,
          ),
          itemCount: _collectedPosts.length + (_hasMore ? 1 : 0),
          itemBuilder: (context, index) {
            if (index >= _collectedPosts.length) {
              // 加载更多条目
              return _buildLoadMoreItem();
            }

            final post = _collectedPosts[index];
            return Card(
              margin: const EdgeInsets.symmetric(vertical: 8.0),
              child: InkWell(
                onTap: _isSelecting
                    ? () => _toggleSelection(index)
                    : () => _navigateToPostDetail(post),
                child: ListTile(
                  leading: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.deepOrange.withOpacity(0.1),
                    ),
                    child: const Icon(
                      Icons.collections_bookmark,
                      color: Colors.deepOrange,
                    ),
                  ),
                  title: Text(
                    post.title,
                    style: TextStyle(
                      color: _selectedItems.contains(index)
                          ? Colors.blue : Colors.black,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  subtitle: Text(
                    post.content.length > 30
                        ? '${post.content.substring(0, 30)}...'
                        : post.content,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(color: Colors.grey),
                  ),
                  trailing: _isSelecting
                      ? null
                      : IconButton(
                    icon: const Icon(Icons.delete, color: Colors.grey),
                    onPressed: () => _deleteSingleItem(post.postId),
                  ),
                ),
              ),
            );
          },
        ),

        // 底部操作栏 (仅在选择模式下显示)
        if (_isSelecting)
          Positioned(
            left: 0,
            right: 0,
            bottom: 20,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // 删除按钮
                  Expanded(
                    flex: 5,
                    child: ElevatedButton(
                      onPressed: _deleteSelected,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      child: Text(
                        '删除(${_selectedItems.length})',
                        style: const TextStyle(
                          fontSize: 18,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(width: 20),

                  // 取消按钮
                  Expanded(
                    flex: 5,
                    child: ElevatedButton(
                      onPressed: _toggleSelectMode,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey[300],
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      child: const Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 18,
                          color: Colors.black87,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildLoadMoreItem() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16.0),
      child: Center(
        child: _hasMore
            ? ElevatedButton(
          onPressed: () => _fetchCollections(loadMore: true),
          child: const Text('加载更多'),
        )
            : const Text(
          '没有更多内容了',
          style: TextStyle(color: Colors.grey),
        ),
      ),
    );
  }
}